package com.csylh.service.impl;

import com.csylh.converter.OrderMaster2OrderDTOConverter;
import com.csylh.dao.OrderMasterMapper;
import com.csylh.dto.OrderDTO;
import com.csylh.entity.OrderMaster;
import com.csylh.enums.ResultEnum;
import com.csylh.exception.OrderException;
import com.csylh.service.OrderService;
import com.csylh.service.UserOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by 留歌
 * Date: 2018/3/13 23:53
 * Description:
 */
@Service
@Slf4j
public class UserOrderServiceImpl  implements UserOrderService{
    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderMasterMapper orderMasterMapper;
    /**
     *  查询单个订单详情
     * @param userId,orderId
     * @return orderDTO
     */
    @Override
    public OrderDTO findOrderOne(String userId, String orderId) {
        return checkOrderOwner(userId,orderId);
    }
    private OrderDTO checkOrderOwner(String userId, String orderId) {
        OrderDTO orderDTO = orderService.findOne(orderId);
        if (orderDTO == null) {
            return null;
        }
        //判断是否是自己的订单
        if (userId.equals(orderDTO.getUserId())) {
            log.error("【查询订单】订单的userId不一致. userId={}, orderDTO={}", userId, orderDTO);
            throw new OrderException(ResultEnum.ORDER_OWNER_ERROR);
        }
        return orderDTO;
    }


    /**
     *  分页查询用户所有订单
     * @param UserUserId,pageable
     * @return
     */
    @Override
    public Page<OrderDTO> findList(String UserUserId, Pageable pageable) {
        //TODO 通过UserId来分页查询订单列表
        Page<OrderMaster> orderMasterPage = orderMasterMapper.findByUserUserId(UserUserId, pageable);

        List<OrderDTO> orderDTOList = OrderMaster2OrderDTOConverter.convert(orderMasterPage.getContent());

        return new PageImpl<OrderDTO>(orderDTOList, pageable, orderMasterPage.getTotalElements());
    }


    @Override
    public OrderDTO cancelOrder(String userId, String orderId) {
        OrderDTO orderDTO = checkOrderOwner(userId, orderId);
        if (orderDTO == null) {
            log.error("【取消订单】查不到改订单, orderId={}", orderId);
            throw new OrderException(ResultEnum.ORDER_NOT_EXIST);
        }
        return orderService.cancel(orderDTO);
    }
}
